package middleware

import (
	"context"
	"net/http"
	"strconv"

	"gitee.com/kessil/chicory/internal/config"
)

const (
	PaginationKey contextKey = "pagination"
)

// Pagination 分页信息
type Pagination struct {
	Page     int
	PageSize int
}

// PaginationMiddleware 分页中间件
func PaginationMiddleware(cfg *config.Config) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// 从查询参数获取分页信息
			pageNo, _ := strconv.Atoi(r.URL.Query().Get("pageNo"))
			pageSize, _ := strconv.Atoi(r.URL.Query().Get("pageSize"))
			// 使用配置默认值
			if pageNo <= 0 {
				pageNo = 1
			}
			if pageSize <= 0 {
				pageSize = cfg.CRUD.DefaultPageSize
			}
			if pageSize > cfg.CRUD.MaxPageSize {
				pageSize = cfg.CRUD.MaxPageSize
			}

			// 创建分页信息
			pagination := Pagination{
				Page:     pageNo,
				PageSize: pageSize,
			}

			// 存入上下文
			ctx := context.WithValue(r.Context(), PaginationKey, pagination)
			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

// GetPaginationFromContext 从上下文中获取分页信息
func GetPaginationFromContext(r *http.Request) (int, int) {
	if pagination, ok := r.Context().Value(PaginationKey).(Pagination); ok {
		return pagination.Page, pagination.PageSize
	}
	return 1, 10 // 默认值
}
